package controller

import (
	"fmt"
	"path"
	"time"

	"github.com/gin-gonic/gin"
	"sxk.games/m/v2/admin/internal/service"
	"sxk.games/m/v2/core/entity"
	"sxk.games/m/v2/core/utils"
)

func UserLogin(c *gin.Context) {

	userInfo := map[string]any{
		"roles":        []string{"admin"},
		"introduction": "I am a super administrator",
		"avatar":       "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
		"name":         "Super Admin",
	}

	utils.ResponseJson(c, nil, userInfo)
}

func UserInfo(c *gin.Context) {

	userInfo := map[string]any{
		"roles":        []string{"admin"},
		"introduction": "I am a super administrator",
		"avatar":       "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
		"name":         "Super Admin",
	}

	utils.ResponseJson(c, nil, userInfo)
}

func UserLogout(c *gin.Context) {
	utils.ResponseJson(c, nil, nil)
}

/**
 * @Author: jingguang.Xu
 * @description: 添加用户
 * @param {*gin.Context} c
 * @return {*}
 */
func AddUser(c *gin.Context) {
	// 提取上传的文件
	mFile, err := c.FormFile("file")
	if err != nil {
		utils.ResponseJson(c, fmt.Errorf("上传文件错误："+err.Error()), nil)
		return
	}
	uploadPath := "upload"
	// 存储文件
	filename := fmt.Sprintf("%d%s", time.Now().UnixNano(), path.Ext(mFile.Filename))
	fmt.Println(filename)
	filePath := path.Join(uploadPath, "images", filename) // 路径
	err = c.SaveUploadedFile(mFile, filePath)
	if err != nil {
		utils.ResponseJson(c, fmt.Errorf("存储文件失败："+err.Error()), nil)
		return
	}
	var username, password string
	username = c.PostForm("username")
	password = c.PostForm("password")
	fmt.Println(username)
	fmt.Println(password)
	// 存储到数据库
	u := &entity.User{
		ID:        fmt.Sprint(time.Now().UnixNano()),
		UserName:  username,
		Password:  password,
		Image:     filePath,
		CreatedAt: time.Now().Unix(),
	}
	if err = service.Impl.User.Insert(u); err != nil {
		utils.ResponseJson(c, err, nil)
		return
	}
	utils.ResponseJson(c, nil, u.ID)
}

/**
 * @Author: jingguang.Xu
 * @description: 获取用户列表
 * @param {*gin.Context} c
 * @return {*}
 */
func GetUsers(c *gin.Context) {
	users, err := service.Impl.User.Gets()
	if err != nil {
		utils.ResponseJson(c, err, nil)
		return
	}
	utils.ResponseJson(c, nil, users)
}
